
import React, { useState } from 'react';
import { useLocalization } from '../hooks/useLocalization';
import type { DownloadResult } from '../types';
import { PasteIcon, DownloadIcon, LoadingIcon } from './icons';

interface DownloaderFormProps {
  toolName: string;
}

const DownloaderForm: React.FC<DownloaderFormProps> = ({ toolName }) => {
    const { t } = useLocalization();
    const [url, setUrl] = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [result, setResult] = useState<DownloadResult | null>(null);

    const handlePaste = async () => {
        try {
            const text = await navigator.clipboard.readText();
            setUrl(text);
        } catch (err) {
            setError(t('paste_error'));
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!url.trim()) {
            setError(t('url_required_error'));
            return;
        }
        setError(null);
        setResult(null);
        setLoading(true);

        try {
            const response = await fetch('https://api.daobt.com/get_all_video_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ url }),
            });

            if (!response.ok) {
                throw new Error(t('download_error'));
            }

            const data = await response.json();

            if (data.status !== 'success') {
                throw new Error(data.message || t('invalid_url_error'));
            }

            setResult({
                thumbnailUrl: data.thumbnail,
                videoUrl: data.best_merged_url,
                videoOnlyUrl: data.best_video_url,
                audioOnlyUrl: data.best_audio_url,
                title: data.title,
            });
        } catch (err) {
            console.error("Download failed:", err);
            setError(err instanceof Error ? err.message : String(err));
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="w-full max-w-3xl mx-auto">
            <form onSubmit={handleSubmit} className="bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-lg transition-all duration-300">
                <div className="relative flex flex-col sm:flex-row items-center gap-3">
                    <div className="relative w-full">
                         <input
                            type="text"
                            value={url}
                            onChange={(e) => setUrl(e.target.value)}
                            placeholder={t('paste_url_placeholder', { tool: toolName })}
                            className="w-full h-16 pl-5 pr-16 text-lg bg-gray-100 dark:bg-gray-700 border-2 border-transparent focus:border-primary focus:ring-0 rounded-xl transition-colors duration-200"
                            disabled={loading}
                        />
                         <button
                            type="button"
                            onClick={handlePaste}
                            className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-primary dark:hover:text-primary-light transition-colors"
                            aria-label="Paste URL"
                        >
                            <PasteIcon />
                        </button>
                    </div>
                    <button
                        type="submit"
                        disabled={loading}
                        className="w-full sm:w-auto h-16 px-8 flex items-center justify-center bg-primary hover:bg-primary-dark text-white font-bold text-lg rounded-xl transition-all duration-300 transform hover:scale-105 disabled:bg-gray-400 disabled:cursor-not-allowed disabled:transform-none"
                    >
                        {loading ? <LoadingIcon /> : <DownloadIcon />}
                        <span className="ml-2">{loading ? t('downloading_button') : t('download_button')}</span>
                    </button>
                </div>
            </form>

            {error && (
                <div className="mt-4 p-4 bg-red-100 dark:bg-red-900/50 text-red-700 dark:text-red-300 border border-red-200 dark:border-red-800 rounded-lg text-center">
                    {error}
                </div>
            )}

            {result && !error && (
                <div className="mt-8 bg-white dark:bg-gray-800 p-6 rounded-2xl shadow-lg animate-fade-in">
                    <h3 className="text-xl font-bold mb-4 text-center">{t('download_ready')}</h3>
                    <div className="flex flex-col md:flex-row items-center gap-6">
                        <img src={result.thumbnailUrl} alt="Video thumbnail" className="w-full md:w-64 h-auto rounded-lg shadow-md" />
                        <div className="flex-1 text-center md:text-left w-full">
                            <p className="text-lg font-semibold mb-4">{result.title}</p>
                            <div className="flex flex-wrap justify-center md:justify-start gap-3">
                                {result.videoUrl && (
                                    <a
                                        href={result.videoUrl}
                                        download
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="inline-flex items-center justify-center h-11 px-5 bg-green-500 hover:bg-green-600 text-white font-bold text-base rounded-xl transition-all duration-300 transform hover:scale-105"
                                    >
                                        <DownloadIcon />
                                        <span className="ml-2">{t('download_video_hd')}</span>
                                    </a>
                                )}
                                {result.videoOnlyUrl && (
                                    <a
                                        href={result.videoOnlyUrl}
                                        download
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="inline-flex items-center justify-center h-11 px-5 bg-blue-500 hover:bg-blue-600 text-white font-bold text-base rounded-xl transition-all duration-300 transform hover:scale-105"
                                    >
                                        <DownloadIcon />
                                        <span className="ml-2">{t('download_video_only')}</span>
                                    </a>
                                )}
                                {result.audioOnlyUrl && (
                                    <a
                                        href={result.audioOnlyUrl}
                                        download
                                        target="_blank"
                                        rel="noopener noreferrer"
                                        className="inline-flex items-center justify-center h-11 px-5 bg-gray-600 hover:bg-gray-700 text-white font-bold text-base rounded-xl transition-all duration-300 transform hover:scale-105"
                                    >
                                        <DownloadIcon />
                                        <span className="ml-2">{t('download_audio_only')}</span>
                                    </a>
                                )}
                            </div>
                             <p className="text-xs text-gray-500 dark:text-gray-400 mt-3">{t('download_disclaimer')}</p>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default DownloaderForm;